/**
 * 重复请求测试工具
 * 用于验证重复请求修复效果
 */

import { requestDebugger } from './requestDebugger';
import { requestGuard } from './requestGuard';

interface TestResult {
  testName: string;
  passed: boolean;
  details: string;
  requestCounts: Record<string, number>;
  duplicateCount: number;
}

class DuplicateRequestTest {
  private results: TestResult[] = [];

  /**
   * 测试页面加载时的重复请求
   */
  async testPageLoadDuplicates(pageName: string): Promise<TestResult> {
    console.log(`\n🧪 测试 ${pageName} 页面加载重复请求...`);
    
    // 清除之前的记录
    requestDebugger.clear();
    requestGuard.clearAll();
    
    // 等待页面加载完成
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    const stats = requestDebugger.getRequestStats();
    const requestCounts = stats?.requestCounts || {};
    
    // 计算重复请求数量
    let duplicateCount = 0;
    const duplicateEndpoints: string[] = [];
    
    Object.entries(requestCounts).forEach(([endpoint, count]) => {
      if (count > 1) {
        duplicateCount += count - 1;
        duplicateEndpoints.push(`${endpoint} (${count}次)`);
      }
    });
    
    const passed = duplicateCount === 0;
    const details = passed 
      ? `✅ 无重复请求` 
      : `❌ 发现 ${duplicateCount} 个重复请求: ${duplicateEndpoints.join(', ')}`;
    
    const result: TestResult = {
      testName: `${pageName} 页面加载`,
      passed,
      details,
      requestCounts,
      duplicateCount,
    };
    
    this.results.push(result);
    console.log(details);
    
    return result;
  }

  /**
   * 测试搜索操作的重复请求
   */
  async testSearchDuplicates(pageName: string): Promise<TestResult> {
    console.log(`\n🔍 测试 ${pageName} 搜索重复请求...`);
    
    requestDebugger.clear();
    
    // 模拟快速搜索
    const searchInput = document.querySelector('input[placeholder*="搜索"]') as HTMLInputElement;
    if (searchInput) {
      // 快速输入多个字符
      ['t', 'te', 'tes', 'test'].forEach((value, index) => {
        setTimeout(() => {
          searchInput.value = value;
          searchInput.dispatchEvent(new Event('input', { bubbles: true }));
        }, index * 50);
      });
    }
    
    // 等待防抖完成
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const stats = requestDebugger.getRequestStats();
    const requestCounts = stats?.requestCounts || {};
    
    // 统计搜索相关的请求
    const searchRequests = Object.entries(requestCounts).filter(([endpoint]) => 
      endpoint.includes('/users') || endpoint.includes('/roles')
    );
    
    const totalSearchRequests = searchRequests.reduce((sum, [, count]) => sum + count, 0);
    const passed = totalSearchRequests <= 1; // 期望最多1个搜索请求
    
    const details = passed 
      ? `✅ 搜索防抖正常，发送 ${totalSearchRequests} 个请求` 
      : `❌ 搜索防抖失效，发送 ${totalSearchRequests} 个请求`;
    
    const result: TestResult = {
      testName: `${pageName} 搜索操作`,
      passed,
      details,
      requestCounts,
      duplicateCount: Math.max(0, totalSearchRequests - 1),
    };
    
    this.results.push(result);
    console.log(details);
    
    return result;
  }

  /**
   * 测试分页操作的重复请求
   */
  async testPaginationDuplicates(pageName: string): Promise<TestResult> {
    console.log(`\n📄 测试 ${pageName} 分页重复请求...`);
    
    requestDebugger.clear();
    
    // 模拟分页点击
    const paginationButtons = document.querySelectorAll('.ant-pagination-item');
    if (paginationButtons.length > 1) {
      (paginationButtons[1] as HTMLElement).click();
    }
    
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const stats = requestDebugger.getRequestStats();
    const requestCounts = stats?.requestCounts || {};
    
    // 统计数据请求
    const dataRequests = Object.entries(requestCounts).filter(([endpoint]) => 
      endpoint.includes('/users') || endpoint.includes('/roles')
    );
    
    // 统计配置请求（不应该在分页时发送）
    const configRequests = Object.entries(requestCounts).filter(([endpoint]) => 
      endpoint.includes('/permissions') && !endpoint.includes('page')
    );
    
    const totalDataRequests = dataRequests.reduce((sum, [, count]) => sum + count, 0);
    const totalConfigRequests = configRequests.reduce((sum, [, count]) => sum + count, 0);
    
    const passed = totalDataRequests === 1 && totalConfigRequests === 0;
    
    const details = passed 
      ? `✅ 分页正常，数据请求 ${totalDataRequests} 个，配置请求 ${totalConfigRequests} 个` 
      : `❌ 分页异常，数据请求 ${totalDataRequests} 个，配置请求 ${totalConfigRequests} 个`;
    
    const result: TestResult = {
      testName: `${pageName} 分页操作`,
      passed,
      details,
      requestCounts,
      duplicateCount: Math.max(0, totalDataRequests - 1) + totalConfigRequests,
    };
    
    this.results.push(result);
    console.log(details);
    
    return result;
  }

  /**
   * 运行完整测试套件
   */
  async runFullTest(): Promise<TestResult[]> {
    console.log('🚀 开始重复请求测试...');
    
    const pages = ['UserManagement', 'RoleManagement'];
    
    for (const page of pages) {
      try {
        await this.testPageLoadDuplicates(page);
        await this.testSearchDuplicates(page);
        await this.testPaginationDuplicates(page);
      } catch (error) {
        console.error(`${page} 测试失败:`, error);
      }
    }
    
    this.printSummary();
    return this.results;
  }

  /**
   * 打印测试总结
   */
  private printSummary(): void {
    console.log('\n📊 重复请求测试总结:');
    console.log('='.repeat(60));
    
    const passedTests = this.results.filter(r => r.passed).length;
    const totalTests = this.results.length;
    const totalDuplicates = this.results.reduce((sum, r) => sum + r.duplicateCount, 0);
    
    this.results.forEach(result => {
      const status = result.passed ? '✅' : '❌';
      console.log(`${status} ${result.testName}: ${result.details}`);
    });
    
    console.log('='.repeat(60));
    console.log(`测试结果: ${passedTests}/${totalTests} 通过`);
    console.log(`重复请求总数: ${totalDuplicates}`);
    
    if (passedTests === totalTests && totalDuplicates === 0) {
      console.log('🎉 所有测试通过，无重复请求！');
    } else {
      console.log('⚠️ 存在重复请求问题，需要进一步优化');
    }
  }

  /**
   * 获取RequestGuard状态
   */
  getGuardStatus(): void {
    console.log('\n🛡️ RequestGuard 状态:');
    const status = requestGuard.getGuardStatus();
    
    if (Object.keys(status).length === 0) {
      console.log('无活动的请求防护');
    } else {
      Object.entries(status).forEach(([key, guard]) => {
        console.log(`${key}: ${guard.isLoading ? '🔄 加载中' : '✅ 空闲'} (上次请求: ${new Date(guard.lastRequestTime).toLocaleTimeString()})`);
      });
    }
  }

  /**
   * 强制重置所有防护
   */
  resetAllGuards(): void {
    requestGuard.clearAll();
    console.log('🔄 已重置所有请求防护');
  }

  /**
   * 清除测试结果
   */
  clear(): void {
    this.results = [];
    console.log('🗑️ 已清除测试结果');
  }
}

// 创建全局实例
export const duplicateRequestTest = new DuplicateRequestTest();

// 在开发环境下暴露到window对象
if (process.env.NODE_ENV === 'development') {
  (window as any).duplicateRequestTest = duplicateRequestTest;
}
